//
// Created by 123 on 2024/3/1.
//
#include <iostream>

using namespace std;

//typedef 是起别名的关键字
typedef struct LNode {
    int data;
    struct LNode *next;
} LNode, *LinkedList;

//初始化链表
bool initList(LinkedList &L);

//链表长度
int length(LinkedList L);

//按序号查找节点
LNode *getElem(LinkedList L, int i);

//按值查找节点
LNode *localeElem(LinkedList L, int e);

//插入
bool listInsert(LinkedList &L, int i, int e);

//删除
bool listDelete(LinkedList &L, int i, int &e);


void show(LinkedList L);


int main() {
    LinkedList L;
    initList(L);

    listInsert(L, 1, 1);
    listInsert(L, 2, 2);
    listInsert(L, 3, 3);
    listInsert(L, 4, 4);
    listInsert(L, 5, 5);
    listInsert(L, 6, 6);
    listInsert(L, 77, 7);
    listInsert(L, 1, -1);
    listInsert(L, 3, 11);


    cout << length(L) << endl;


    show(L);
    cout << getElem(L, 3)->data << "    <==============" << endl;
    cout << localeElem(L, 11)->data << "    <==============" << endl;

    int e;
    listDelete(L, 1, e);
    cout << e << "  <-------------" << endl;
    show(L);
    listDelete(L, 2, e);
    cout << e << "  <-------------" << endl;
    show(L);
    listDelete(L, 7, e);
    cout << e << "  <-------------" << endl;
    show(L);


}

bool initList(LinkedList &L) {
    L = (LNode *) malloc(sizeof(LNode));
    L->next = NULL;
    return true;
}

int length(LinkedList L) {
    int len = 0;
    while (L->next != NULL) {
        L = L->next;
        len++;
    }
    return len;
}

LNode *getElem(LinkedList L, int i) {
    int j = 1;
    while (L->next != NULL && j <= i) {
        L = L->next;
        j++;
    }
    return L;
}

LNode *localeElem(LinkedList L, int e) {
    while (L != NULL && L->data != e) {
        L = L->next;
    }
    return L;
}

bool listInsert(LinkedList &L, int i, int e) {
    int len = length(L);
    if (i < 1)
        i = 0;
    if (i > len)
        i = len + 1;
    LNode *p = L;
    int j = 0;
    while (p != NULL && j < i - 1) {
        j++;
        p = p->next;
    }
    LNode *n = (LNode *) malloc(sizeof(LNode));
    n->next = p->next;
    n->data = e;
    p->next = n;
    return true;
}

bool listDelete(LinkedList &L, int i, int &e) {
    if (i < 1 || i > length(L))
        return false;
    LNode *p = L;
    int j = 0;

    while (p != NULL && j < i - 1) {
        p = p->next;
        j++;

    }
    LNode *node = p->next;
    p->next = node->next;
    e=node->data;
    free(node);
    return true;
}

void show(LinkedList L) {
    while (L->next != NULL) {
        L = L->next;
        cout << L->data << ":    ";
    }
    cout << endl;
}